package encaps.action;

import encaps.entities.Grant;
import encaps.entities.MovieLocal;
import encaps.entities.MovieLocalHome;
import encaps.logging.JMSUtil;
import encaps.logging.Log;
import encaps.resources.Labels;
import encaps.utils.EntityUtil;
import encaps.utils.SystemException;
import encaps.utils.XMLHelper;
import java.util.Date;
import java.util.HashMap;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import javax.naming.NamingException;
import org.jdom.Element;

public class CreateCommentAction extends Action {

    public static final String CREATE_COMMENT = "createComment";
    public static final String CONTENT = "commentContent";
    protected ActionContext actionContext;

    public CreateCommentAction(ActionContext context, Grant requiredGrant) {
        this.actionContext = context;
        this.requiredGrant = requiredGrant;
    }

    @Override
    public Element execute() throws ActionExecutionException {
        try {
            Long movie_id = Long.valueOf(actionContext.getTextParameter(ID));
            MovieLocalHome movieHome = EntityUtil.getMovieHome();
            String username = actionContext.getUserLogin();
            MovieLocal movie = movieHome.findByPrimaryKey(movie_id);
            Long uid = EntityUtil.getUserHome().findByLogin(username).getID();
            String message = actionContext.getTextParameter(CONTENT);

            Long cid = movie.addComment(uid, message, new Date());


            JMSUtil.sendLogMessage(Log.INSERT,
                    uid,
                    username, new Date(), "comment",
                    cid, movie_id.toString());

            return XMLHelper.toXMLElement(movie, Labels.getLabel(Labels.VIEW_MOVIE),
                    false, username, actionContext.getUserRole(), new HashMap<String, String>());
        } catch (SystemException ex) {
            throw new ActionExecutionException("Cannot execute action", ex);
        } catch (NamingException ex) {
            throw new ActionExecutionException("Cannot execute action", ex);
        } catch (FinderException ex) {
            throw new ActionExecutionException("Cannot execute action", ex);
        } catch (CreateException ex) {
            throw new ActionExecutionException("Cannot execute action", ex);
        }

    }
}
